package com.wcity.manage.web.community;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.permit.PermitVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.permit.Permit;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.permit.PermitService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 证件类型
 * Created by hgg on 2016/12/17.
 */
@Controller
public class PermitAct {

    private final static Logger log = LoggerFactory.getLogger(PermitAct.class);

    @Autowired
    private PermitService permitService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private BlockService blockService;

    /**
     * 证件类型列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/community_permit_list")
    public String permitList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage());
            requestMap.put( "userId", user.getId() );
            List<PermitVo> permitVos = permitService.permitPageList( requestMap );

            //【4】查询总数量
            Integer totalPermit = permitService.totalPermit( requestMap );
            model.setTotal( totalPermit );

            request.setAttribute( "permits", permitVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "permitName", requestMap.get( "permitName" ) );
        } catch ( Exception e ) {
            log.error( "查询证件类型列表异常:" + e.getMessage() );
        }
        return "community/permit/list";
    }

    /**
     * 执行删除证件类型
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_permit")
    @ResponseBody
    public void deletePermit( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】执行删除
            Integer deleteNum = permitService.deletePermit( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除证件类型异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增证件类型
     *
     * @param permit
     * @param response
     */
    @RequestMapping(value = "save_add_community_permit")
    @ResponseBody
    public void addPermit( Permit permit, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            if ( StringUtils.isBlank( permit.getPermitName() ) ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }

            //【3】执行保存证件类型
            permit.setUserId(user.getId());
            permitService.saveAddPermit(permit);

        } catch ( Exception e ) {
            log.error( "保存证件类型异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_permit_list", "", "closeCurrent", ""));
    }

    /**
     * 跳转到编辑证件类型页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_permit")
    public String permitDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询证件类型数据
            requestMap.put("userId", user.getId());
            PermitVo permitVo = permitService.permitDetail(requestMap);
            request.setAttribute("permit", permitVo);
            if (permitVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

        } catch ( Exception e ) {
            log.error( "查询证件类型失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/permit/edit";
    }

    /**
     * 更新证件类型
     *
     * @param permit
     * @param response
     */
    @RequestMapping(value = "save_edit_community_permit")
    @ResponseBody
    public void updatePermit(Permit permit, HttpServletResponse response, HttpServletRequest request) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            if (StringUtils.isBlank(permit.getPermitName())) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if (user == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }

            //【3】执行更新证件类型
            permit.setUserId( user.getId() );
            Integer updateNum = permitService.saveUpdatePermit( permit );
            if ( updateNum == 0 ) {
                throw new RuntimeException( "更新证件类型失败" );
            }

        } catch ( Exception e ) {
            log.error( "更新证件类型异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_permit_list", "", "closeCurrent", ""));
    }

    /**
     * 跳转到添加证件类型的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_permit")
    public String toAddPermit(){

        return "community/permit/add";
    }


    /*********************************************H5端请求****************************************/

    /**
     * 证件类型列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "v1/community_permit_list_h5")
    @ResponseBody
    public Object permitListH5( HttpServletRequest request, PageModel model ) {


        //【1】封装参数/参数校验
        Map<String,Object> requestMap = new HashedMap();
        String registerId = request.getParameter( "registerId" );
        if( StringUtils.isBlank( registerId ) ){
            throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
        }

        //【2】获取当前用户信息
        Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
        if( userMap == null || userMap.get( "blockId" ) == null ){
            throw new CustomException( "用户信息不存在", Code.ERROR );
        }

        //【3】查询小区
        Integer blockId = (Integer) userMap.get( "blockId" );
        Block block = blockService.getBlockById( blockId );

        //【4】查询数据
        requestMap.put( "userId",block.getUserId() );
        requestMap.put( "start", 0 );
        requestMap.put( "end", 1000 );
        List<PermitVo> permitVos = permitService.permitPageList( requestMap );
        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put( "permits",permitVos );

        return map;
    }
}
